package com.ouc.yyi.controller;

import com.ouc.yyi.config.model.Menu;
import com.ouc.yyi.config.model.SysUser;
import com.ouc.yyi.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class loginController {
    @Autowired
    private MenuService menuService;
    @GetMapping("/index")
    public String index(){
        return "index.html";
    }
    @RequestMapping("/login")
    public String login(){
        return "login.html";
    }
    @RequestMapping("/loginUser")
    public String loginUser(@RequestParam("username")String username,
                            @RequestParam("password") String password, HttpSession session, Model model){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try{
            //进行登陆
            subject.login(usernamePasswordToken);
            //登陆成功后获得到用户
            SysUser user = (SysUser)subject.getPrincipal();
            List<Menu> list = menuService.getMenuByRoleId(user.getRoleId());
            if (list.size()==0){
                model.addAttribute("tip","改用户没有分配权限");
                return "login.html";
            }
            //放到session中去,在授权中获得
            session.setAttribute("user",user);
           /* if (user.getRoleId()==null){
                session.setAttribute("tip","该用户没有进行角色分配");
                return "login.html";
            }*/
            return "redirect:" + "/index";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("tip","用户名或者密码错误");
            e.printStackTrace();
            return "login.html";
        }catch (UnknownAccountException e){
            model.addAttribute("tip","没有找到改用户");
            e.printStackTrace();
            return "login.html";
        }
    }
}
